package com.xiaohai.wx.weather.service;

import com.xiaohai.wx.weather.service.LocationService;
import com.xiaohai.wx.weather.test.LocationGenerator;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

@Service("LocationService")
public class LocationService {

	private List<String> cityNameList = new ArrayList<String> ();
	
	Map<String, String> cityNameCodeMap = new HashMap<String, String>();
    Map<String, String> countyNameCodeMap = new HashMap<String, String>();
    Map<String, String> districtNameCodeMap = new HashMap<String, String>();
    Map<String, String> qiNameCodeMap = new HashMap<String, String>();
    Map<String, String> otherNameCodeMap = new HashMap<String, String>();
	
	private Logger logger = Logger.getLogger(this.getClass());

	public LocationService() throws IOException{
		this.initializeCityMap();
	}
	
	private void initializeCityMap() throws IOException {

		InputStream in = LocationGenerator.class.getClassLoader()
                .getResourceAsStream("location.txt");
        InputStreamReader isr = new InputStreamReader(in, "UTF-8");
        BufferedReader br = new BufferedReader(isr);
        String line = null;
        int i=0;
        String cityName;
        String cityCode;
        
        while ((line = br.readLine()) != null && i<5000) {
            //System.out.println(line);
            if(StringUtils.isNotBlank(line)){
            	cityName = line.substring(0, line.indexOf("="));
            	cityCode = line.substring(line.indexOf("=")+1, line.length());
            	String trimName = cityName;
            	if(cityName.length()> 2 && (cityName.endsWith("市") || 
            			cityName.endsWith("县") || cityName.endsWith("区") || cityName.endsWith("旗") )){
            		trimName = cityName.substring(0, cityName.length()-1);
            	}
            	
            	if(cityName.endsWith("市")){
            		cityNameCodeMap.put(trimName, cityCode);
            	}else if(cityName.endsWith("县")){
            		countyNameCodeMap.put(trimName, cityCode);
            	}else if(cityName.endsWith("区")){
            		districtNameCodeMap.put(trimName, cityCode);
            	}else if(cityName.endsWith("旗")){
            		qiNameCodeMap.put(trimName, cityCode);
            	}else{
            		otherNameCodeMap.put(trimName, cityCode);
            	}	
            	
            	cityNameList.add(trimName);
            }
            i++;
        } 
        br.close();
        isr.close();
        in.close();  
	}

	@Deprecated
	public String getCityCode(String cityName) {
		return this.cityNameCodeMap.get(cityName);
	}
	
	public List<String> getLocationFromStr(String input){

		List<String> countyList = new ArrayList<String>();
		List<String> districtList = new ArrayList<String>();
		List<String> qiList = new ArrayList<String>();
		List<String> cityList = new ArrayList<String>();
		List<String> otherList = new ArrayList<String>();
		
		boolean countyFlag=true, districtFlag=true, cityFlag = true, qiFlag = true;
		
		if(input.contains("县")){
			input = getLocationFromMap(input, countyNameCodeMap, countyList);
			input = input.replace("县", "");
			countyFlag = false;
		}
		if(input.contains("区")){
			input = getLocationFromMap(input, districtNameCodeMap, districtList);
			input = input.replace("区", "");
			districtFlag = false;
		}
		if(input.contains("旗")){
			input = getLocationFromMap(input, qiNameCodeMap, qiList);
			input = input.replace("旗", "");
			qiFlag = false;
		}
		if(input.contains("市")){
			input = getLocationFromMap(input, cityNameCodeMap, cityList);
			input = input.replace("市", "");
			cityFlag = false;
		}
		
		if(!input.equals("") && cityFlag){
			input = getLocationFromMap(input, cityNameCodeMap, cityList);
		}
		if(!input.equals("") && countyFlag){
			input = getLocationFromMap(input, countyNameCodeMap, countyList);
		}
		if(!input.equals("") && qiFlag){
			input = getLocationFromMap(input, qiNameCodeMap, qiList);
		}
		if(!input.equals("") && districtFlag){
			input = getLocationFromMap(input, districtNameCodeMap, districtList);
		}
		if(!input.equals("") ){
			input = getLocationFromMap(input, otherNameCodeMap, otherList);
		}
		
		cityList.addAll(countyList);
		cityList.addAll(districtList);
		cityList.addAll(qiList);
		cityList.addAll(otherList);
		
		return cityList;
		
	}
	
	private String getLocationFromMap(String input, Map<String, String> map, List<String> locationList){
		
		for(Map.Entry<String, String> entry: map.entrySet()){
			if(input.contains(entry.getKey())){
				input = input.replaceAll(entry.getKey(), "");
				locationList.add(entry.getKey());
			}
		}		
		return input;		
	}

	@Deprecated
	Map<String, String> getLocationFrom(String input) {
		
		Map<String, String> locationMap = new HashMap<String,String>();
		Map<String, ArrayList<String>> codeMap = new HashMap<String, ArrayList<String>>();
		
		for (Map.Entry<String, String> entry : cityNameCodeMap.entrySet()) {
			if(input.contains(entry.getKey())){
				input = input.replace(entry.getKey(), "");
				String truncatedCode = entry.getValue().substring(0, 5);
				if(codeMap.containsKey(truncatedCode)){
					ArrayList<String> realCodeList = codeMap.get(truncatedCode);
					
					for(String realCode: realCodeList){
						if(realCode.equalsIgnoreCase(truncatedCode+"0100")){
							realCodeList.remove(realCode);
							locationMap.remove(realCode);
						}
					}
					realCodeList.add(entry.getValue());	
					locationMap.put(entry.getKey(), entry.getValue());
					
				}else{
					
					ArrayList<String> realCodeList = new ArrayList<String>();
					realCodeList.add(entry.getValue());
					codeMap.put(truncatedCode, realCodeList);
					locationMap.put(entry.getKey(), entry.getValue());
				}
			}
		}
		return locationMap;
	}
	
	public String getRandomLocationStr(){
		
		StringBuilder result = new StringBuilder();
		for(int i = 0; i< 3; i++){
			int index = RandomUtils.nextInt(cityNameList.size());
			String cityName = cityNameList.get(index);
			result.append(","+ cityName);
			//System.out.println(index);
		}
		return result.substring(1);		
	}
	
	public static void main(String[] args) throws IOException{
		LocationService service = new LocationService();
		System.out.println(service.getLocationFromStr("怀远大同市 "));
		System.out.println(service.getRandomLocationStr());
	}

}
